<template>
    <div>
        <el-card class="box-card">
            <!-- <div slot="header" class="clearfix">
                <span>选择模板：</span><el-select v-model="template" placeholder="请选择" @change="choiceTemplate" size="medium" style="width: 350px;margin-left: 40px;">
                <el-option
                    v-for="(item,index) in templateList"
                    :key="index"
                    :label="item"
                    :value="item"
                    >
                </el-option>
            </el-select>
            </div> -->
            <div>
                <div class="msg-box">
                    <div class="left-msg">
                        <!-- <div style="font-weight: 600;margin-bottom: 30px;">打印预览（{{templateInfo.inventoryType}}）</div> -->
                        <div class="tiaoma">
                            <div class="img-erwei">
                                <!-- <img src="../../../../assets/img/codeImg1.png" class="img1" /> -->
                                <img :src="QRcode" alt="" class="img2" />
                            </div>
                            <div style="margin-left: 20px">{{ templateInfo.inventoryCode }}&nbsp;&nbsp;{{ templateInfo.ypCode }}</div>
                        </div>
                        <div class="msg-muban">
                            <div class="names" style="font-weight: 600; margin-top: 20px">{{ templateInfo.breedName }}</div>
                            <div>
                                <!-- <div class="msg-item" >
                                    <div class="item-left">【属性】</div>
                                    <div class="item-right">中药饮片</div>
                                    <div class="item-right">{{ templateInfo.materialType }}</div>
                                </div> -->
                                <div class="msg-item">
                                    <div class="item-left">【品名】</div>
                                    <div class="item-right">{{ templateInfo.breedName }}</div>
                                </div>
                                <div class="msg-item">
                                    <div class="item-left">【产地】</div>
                                    <div class="item-right">{{ templateInfo.address }}</div>
                                </div>
                                <div class="msg-item">
                                    <div class="item-left">【批号】</div>
                                    <div class="item-right">{{ templateInfo.batch }}</div>
                                </div>
                                <div class="msg-item">
                                    <div class="item-left">【生产日期】</div>
                                    <div class="item-right">{{ templateInfo.scTime }}</div>
                                </div>
                                <div class="msg-item">
                                    <div class="item-left">【保质期】</div>
                                    <div class="item-right">{{ templateInfo.deadLine }}个月</div>
                                </div>
                                <div class="msg-item">
                                    <div class="item-left">【规格】</div>
                                    <div class="item-right">{{ templateInfo.ypUnits }}</div>
                                </div>
                                <!--                                <div class="msg-item">-->
                                <!--                                    <div class="item-left">【包装规格】</div>-->
                                <!--                                    <div class="item-right">{{ templateInfo.packSpec }}</div>-->
                                <!--                                </div>-->
                                <div class="msg-item">
                                    <div class="item-left">【装量】</div>
                                    <div class="item-right">
                                        每袋装{{ decimalFun2(templateInfo.pelletWeight, 1)
                                        }}{{ templateInfo.loadingUnits == 'g' ? '克' : '千克' }}
                                    </div>
                                </div>
                                <div class="msg-item">
                                    <div class="item-left">【贮藏】</div>
                                    <div class="item-right">{{ templateInfo.storage }}</div>
                                </div>
                                <!--                                <div class="msg-item">-->
                                <!--                                    <div class="item-left">【用法与用量】</div>-->
                                <!--                                    <div class="item-right">{{ templateInfo.useWay }}</div>-->
                                <!--                                </div>-->
                                <!--                                <div class="msg-item">-->
                                <!--                                    <div class="item-left">【功能与主治】</div>-->
                                <!--                                    <div class="item-right">{{ templateInfo.effect }}</div>-->
                                <!--                                </div>-->
                                <div class="msg-item">
                                    <div class="item-left">【中药饮片执行标准】</div>
                                    <div class="item-right">{{ templateInfo.zyyp }}</div>
                                </div>
                                <!--                                <div class="msg-item">-->
                                <!--                                    <div class="item-left">中药配方颗粒执行标准</div>-->
                                <!--                                    <div class="item-right">{{templateInfo.checkName}}</div>-->
                                <!--                                </div>-->
                                <!--                                <div class="msg-item">-->
                                <!--                                    <div class="item-left">生产备案号</div>-->
                                <!--                                    <div class="item-right">{{ templateInfo.prodRecordCode }}</div>-->
                                <!--                                </div>-->
                                <!--                                <div class="msg-item">-->
                                <!--                                    <div class="item-left">销售备案号</div>-->
                                <!--                                    <div class="item-right">{{ templateInfo.sellCode }}</div>-->
                                <!--                                </div>-->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </el-card>
        <el-card style="width: 800px; margin: 20px 0">
            <h3 style="margin-bottom: 20px">打印发送</h3>
            <el-row>
                <el-col>
                    <el-form
                        :model="formData"
                        :rules="formRules"
                        ref="form"
                        label-position="left"
                        class="demo-ruleForm"
                        label-width="160px"
                    >
                        <el-form-item label="申请码数：" prop="printNum">
                            <el-input v-model.number="formData.printNum" @change="changeNum" type="number" style="width: 300px"></el-input>
                            &nbsp;&nbsp; 未打印： {{ routerParams.notPrintedNum }} &nbsp;&nbsp; 已打印： {{ routerParams.totalPrintNum }}
                        </el-form-item>
                    </el-form>
                </el-col>
            </el-row>
            <div class="position">
                <el-button type="primary" @click="confirm">提交</el-button>
                <el-button @click="backPage">返回</el-button>
            </div>
        </el-card>
    </div>
</template>

<script>
import { print_findMsg, print_detail, print_send, template_get } from '@/request/api';
import { template_findByCompanyId } from '@/request/manageapi';
import { dateFormat } from '@/utils/time.js';
export default {
    data() {
        return {
            template: '国标',
            templateList: ['国标'],
            templateInfo: {
                inventoryType: '',
                inventoryCode: '',
                ypCode: '',
                breedName: '',
                address: '',
                createTime: '',
                deadLine: '',
                spec: '',
                packSpec: '',
                pelletWeight: '',
                loadingUnits: '',
                storage: '',
                useWay: '',
                effect: '',
                checkName: '',
                prodRecordCode: '',
                sellCode: '',
                prodAddress: ''
            },
            QRcode: '',
            routerParams: {},
            formData: {
                printNum: ''
            },
            formRules: {
                printNum: [{ required: true, message: '不能为空', trigger: 'blur' }]
            },
            keys: {
                品名: 'breedName',
                产地: 'address',
                批号: 'batch',
                生产日期: 'scTime',
                保质期: 'deadLine',
                规格: 'ypUnits',
                装量: 'pelletWeight',
                贮藏: 'storage',
                中药饮片执行标准: 'zyyp'
            }
        };
    },
    mounted() {
        this.$store.commit('setSwitchHeadTab', '中药饮片');
        if (process.env.NODE_ENV === 'development') {
            this.QRcode = 'http://192.168.1.197:81/print/getCodeByBatch?batch=' + this.$route.query.bench;
        } else {
            this.QRcode = 'http://' + window.location.host + '/print/getCodeByBatch?batch=' + this.$route.query.bench;
        }
        console.log('二维码：',this.QRcode);
        this.routerParams = this.$route.query;
        //处理打印发送：未打印-已打印
        this.handleRouterData();
        //根据公司id获取当前饮片模板信息
        this.getTemplateById();
        //获取模板列表
        this.getTemplateList();
    },
    methods: {
        /** @description获取模板列表 **/
        async getTemplateList() {
            let companyId = `?companyId=${localStorage.getItem('companyId')}&isNew=100`;
            const res = await template_findByCompanyId(companyId);
            // console.log(res);
        },
        /** 根据公司id获取当前饮片模板信息  **/
        async getTemplateById() {
            let query = this.routerParams.id;
            const res = await print_findMsg(query);
            try {
                if (res.code == 200) {
                    let temp = {};
                    temp = res.data;
                    temp.scTime = new Date(temp.scTime).toLocaleDateString().replace(/\//g, '.');
                    /** 当前接口改了属性字段，可能会有这些字段 TODO **/
                    if (temp.sellRecord) {
                        temp.sellRecord = JSON.parse(temp.sellRecord);
                        temp.sellCode = temp.sellRecord.filter((item) => item.address == temp.address);
                        temp.sellCode = { ...temp.sellCode }['0'].recordCode;
                    }
                    const {
                        checkId,
                        companyId,
                        factoryName,
                        id,
                        isProduct,
                        loadingQuantity,
                        // materialType,
                        page,
                        pageSize,
                        // prodAddress,
                        sellRecord,
                        status,
                        upperCase,
                        ypCodeStandard,
                        ypQuantity,
                        ...mergedObj
                    } = temp;
                    Object.assign(this.templateInfo, mergedObj);
                } else {
                    this.$message.error(res.msg);
                }
            } catch (e) {
                this.$message.error(e);
                throw e;
            }
        },
        /** @description 选择模板 **/
        choiceTemplate(e) {
            console.log(e);
        },
        /** @description 提交表单 **/
        confirm() {
            this.$refs.form.validate((valid) => {
                if (!valid) return;
                this.$confirm('提交打印数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        let tempObj = {};
                        for (const key in this.keys) {
                            if (key == '保质期') {
                                tempObj[key] = this.templateInfo[this.keys[key]] + '个月';
                            } else if (key == '装量') {
                                let tmp = this.templateInfo.loadingUnits == 'g' ? '克' : '千克';
                                tempObj[key] = '每袋装' + this.decimalFun2(this.templateInfo[this.keys[key]], 1) + tmp;
                            } else if (key == '生产日期') {
                                tempObj[key] = dateFormat(this.templateInfo[this.keys[key]], 'y.m.d');
                            } else {
                                tempObj[key] = this.templateInfo[this.keys[key]];
                            }
                        }
                        let param = {
                            barCode: this.templateInfo.dispenserCode + ' 0 ' + this.templateInfo.batch,
                            breedName: this.templateInfo.breedName,
                            modal: this.templateInfo.inventoryType,
                            type: this.templateInfo.inventoryType.substr(0, 3),
                            url: 'http://sy.xinlvyao.com:10109/zyypScan/index.html?code=',
                            ...tempObj
                        };
                        print_send({
                            printId: this.routerParams.id,
                            printNum: this.formData.printNum,
                            content: JSON.stringify(param)
                        }).then((res) => {
                            if (res.mongoStatus == '1' || res.sendStatus == '1') {
                                this.$notify.error({
                                    title: '提示',
                                    message: res.msg,
                                    showClose: false,
                                    duration: 2000
                                });
                            } else {
                                this.$notify({
                                    title: '提示',
                                    message: '提交成功',
                                    type: 'success',
                                    duration: 1000
                                });
                                this.backPage();
                            }
                        });
                    })
                    .catch((err) => {
                        console.log(err);
                    });
            });
        },
        /** @description 变更打印数验证 **/
        changeNum(val) {
            var num = Math.floor(val);
            if (num <= 0) {
                this.$notify.error({
                    title: '提示',
                    message: '数量不能为零或负数！',
                    showClose: false,
                    duration: 2000
                });
                this.formData.printNum = '';
            }
            if (num > this.routerParams.notPrintedNum) {
                this.$notify.error({
                    title: '提示',
                    message: '数量不能大于未打印数量！',
                    showClose: false,
                    duration: 2000
                });
                this.formData.printNum = '';
            }
        },
        /**
         * 处理未打印已打印from routerParams
         * @param - {endNum} 已打印数
         * @param - {lastPrintNum} 总打印数
         **/
        handleRouterData() {
            this.routerParams.printedNum = Number(this.routerParams.endNum);
            this.routerParams.totalPrintNum = Number(this.routerParams.lastPrintNum);
            this.routerParams.notPrintedNum = Math.abs(Math.round(this.routerParams.printedNum - this.routerParams.totalPrintNum));
        },
        /** @description 取消 **/
        backPage() {
            this.$router.go(-1);
        },

        /**
         * 保留小数位,自动补0
         * @param {*} value 值
         * @param {*} i 保留小数位数
         * @param {*} type 1：四舍五入，2：截取
         */
        decimalFun2(value, i, type) {
            if (!value) return '0';
            if (type == 1) {
                value = (value * 1).toFixed(i);
            } else {
                let pow = Math.pow(10, i);
                value = Math.floor(value * pow) / pow;
            }
            return (value * 1).toFixed(i);
        }
    }
};
</script>

<style lang="less" scoped>
.text {
    font-size: 14px;
}

.item {
    margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
    display: table;
    content: '';
}
.clearfix:after {
    clear: both;
}

.box-card {
    width: 800px;
}
.msg-box {
    width: 100%;
    display: flex;

    .left-msg {
        position: relative;
        width: 100%;
        .tiaoma {
            display: flex;
            align-items: center;
            flex-direction: column;
            position: absolute;
            right: 6%;
            width: 20%;
        }
        .img-erwei {
            width: 100%;
            display: flex;
            justify-content: space-between;
            .img1 {
                display: block;
                width: 60%;
                height: 80%;
            }
            .img2 {
                width: 100%;
                display: block;
            }
        }
    }
}
.msg-item {
    width: 100%;
    display: flex;
    margin: 10px 0;
    .item-left {
        width: 30%;
        font-size: 16px;
        color: #777777;
    }
    .item-right {
        flex: 1;
        font-size: 16px;
        font-weight: 500;
        color: black;
    }
}
.position {
    width: 100%;
    position: fixed;
    bottom: 0;
    padding: 20px;
}
</style>
